/* 
 * File:   IceApp.h
 * Author: xuqian
 *
 * Created on December 29, 2014, 6:50 PM
 */

#ifndef ICEAPP_H
#define	ICEAPP_H

#include <netinet/in.h>
#include "common/TwLog.h"
#include <common/ReadWriteMutex.h>
#include "Ice.h"
#include <vector>
#include <map>
using namespace std;

struct ConfigIceConnectivity {
    bool useCandidate;
    int  timerInterval;
    int  roleType;
    std::string  userName;
    std::string  roleValue;
    std::string  priority;
    std::string  password;
};

struct ConfigIceKeepAlive {
    int  timerInterval;
};

class AnotherTimerTask;
class AnotherMultiTimerThread;

enum SbIceStackActions {
     mpIceConnectivityCheck = 215, // ICE connectivity check
     mpIceKeepAliveEnable = 216 // ICE keep-alive
};
    
class IceApp {
public:
    IceApp(int sockId);
    virtual ~IceApp();
    
    virtual int handleIceCommand(int actid, char *buf, int size);
    int getSocketId() {return mSockId;}
    void setDestination(in6_addr *destAddr, unsigned short destPort);
    void onT_ConnCheck(int timer_id);
    void onT_KeepAlive(int timer_id);
    int handleIceData(char *msg, int len);
    
protected:
    int IceConnnectivityCheck(ConfigIceConnectivity* pConfig);
    int IceKeepAlive(ConfigIceKeepAlive* pConfig);
    int getIceConnCheckValues(byte* buf, int size, ConfigIceConnectivity* pConfig);
    int getIceKeepAliveValues(byte* buf, int size, ConfigIceKeepAlive* pConfig);
    int IceConnCheckCommand(byte* command_buffer, int size);
    int IceKeepAliveCommand(byte* command_buffer, int size);
    bool InitTimerManager();
    void ReleaseTimerManager();
    void ReleaseConnCheckMap();
    void ReleaseKeepAliveMap();
    void CleanUp();
    ConfigIceConnectivity * findIceConnCheckConfig(int timerId);
    ConfigIceKeepAlive * findIceKeepAliveConfig(int timerId);
    
    int assembleStunConnCheckMsg(char* outBuffer, int maxOutBufSize, ConfigIceConnectivity* pConfig);
    int assembleStunKeepAliveMsg(char* outBuffer, int maxOutBufSize, ConfigIceKeepAlive* pConfig);
   
private:
    TwLog log;
    bool timerRunning;
    int  mSockId;
    IcePackage icePkt;
    struct sockaddr_in6 udpAddr;
    AnotherMultiTimerThread *timerManager; // manager timers    
    map<int, ConfigIceConnectivity *> mConfigConnCheckMap; // configuration of ICE connectivity check
    ReadWriteMutex connCheckMapMutex;          // for access map
    map<int, ConfigIceKeepAlive *> mConfigKeepAliveMap; // configuration of ICE keep-alive
    ReadWriteMutex keepAliveMapMutex;          // for access map

};

#endif	/* ICEAPP_H */

